package xdu.lz.stage2_design_pattern.chapter16_two_phrase_terminated_pattern;

import java.util.Random;

public class CounterIncrement extends Thread {

    private volatile boolean terminated = false;

    private int counter = 0;

    private final static Random random = new Random(System.currentTimeMillis());
    @Override
    public void run() {
        try {
            while (!terminated){
                System.out.println(Thread.currentThread().getName()+" "+(counter++));
                Thread.sleep(random.nextInt(1000));
            }
        } catch (InterruptedException e){
            System.out.println("被中断");
        }finally {
            this.clean();
        }
    }

    private void clean(){
        System.out.println("do some clean work for the second phase... counter = "+counter);
    }

    public void close(){
        this.terminated = true;
        //去唤醒所有没有机会判断terminated标志的线程
        this.interrupt();
    }
}
